﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net.Sockets;
using System.Net;

namespace RadarMonitor.StatusMonitor
{
    public class StatusMonitor
    {

        #region 单例
        private static readonly Lazy<StatusMonitor>
            lazy =
            new Lazy<StatusMonitor>
                (() => new StatusMonitor());

        public static StatusMonitor Instance { get { return lazy.Value; } }

        private StatusMonitor()
        {
            try
            {
                receivingUdpClient = new UdpClient(14080);
            }
            catch { }
        }
        #endregion

        public event Action<bool> RDAComunicationEevent;
        public event Action<string> RDAAlarmEvent;

        private string rdaIP = "10.78.135.220";
        private int rdaPort = 14081;
        private UdpClient receivingUdpClient;
        private bool running = false;
        private int hearBeatCnt = 2;
        // 发送心跳间隔（单位秒）
        public int QueryInterval { get; set; } = 1 * 3;

        private Timer loopTimer = null;

        public void Start()
        {
            if (loopTimer != null)
                return;
            loopTimer = new Timer(CheckLoop, null, 0, QueryInterval * 1000);

            running = true;
            hearBeatCnt = 3;
            Task.Run(() => {
                while (running)
                {
                    if(receivingUdpClient == null)
                    {
                        try {
                            receivingUdpClient = new UdpClient(14080);
                        }
                        catch { }
                    }
                    try
                    {
                        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Parse(rdaIP), 0);
                        Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
                        string returnData = Encoding.ASCII.GetString(receiveBytes);
                        Console.WriteLine($"rec udp {returnData}");
                        hearBeatCnt = 0;
                        if (returnData.StartsWith("RDA_Monitor")) { }//心跳包

                        if (returnData.Contains("ALARM")) //报警
                        {
                            RDAAlarmEvent?.Invoke(returnData);
                        }
                        RDAComunicationEevent?.Invoke(true);
                    }
                    catch { }
                }
            });
        }

        public void Stop()
        {
            loopTimer?.Dispose();
            loopTimer = null;
            try
            {
                running = false;
                receivingUdpClient.Close();
                receivingUdpClient.Dispose();
            }
            catch { }
            finally
            {
                receivingUdpClient = null;
            }
        }

        public void CheckLoop(object info)
        {
            Console.WriteLine($"loop HeartBeat {hearBeatCnt}");
            try
            {
                Byte[] sendBytes = Encoding.ASCII.GetBytes("HeartBeat");
                receivingUdpClient?.Send(sendBytes, sendBytes.Length, rdaIP, rdaPort);
                hearBeatCnt++;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            if(hearBeatCnt >5) //长时间无心跳
            {
                hearBeatCnt = 6;
                RDAComunicationEevent?.Invoke(false);
            }
        }


    }
}
